package cn.itsource.blog.service.impl;

import cn.itsource.blog.domain.Param;
import cn.itsource.blog.mapper.ParamMapper;
import cn.itsource.blog.query.ParamQuery;
import cn.itsource.blog.service.IParamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
// Transactional：用来控制事务的注解；readOnly：只读；propagation：事务传播机制
//  Propagation.SUPPORTS：支持当前事务，如果没有当前事务，就以非事务方法执行
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class ParamServiceImpl implements IParamService {

    @Autowired
    private ParamMapper paramMapper;


    @Transactional
    @Override
    public void add(Param param) {
        paramMapper.add(param);
    }

    @Transactional
    @Override
    public void update(Param param) {

        // 设置更新时间为当前系统时间
        param.setUpdateTime(new Date());

        paramMapper.update(param);
    }

    @Transactional
    @Override
    public void delete(Long id) {
        paramMapper.delete(id);
    }

    @Override
    public Param getOne(Long id) {
        return paramMapper.getOne(id);
    }

    @Override
    public List<Param> getAll() {
        return paramMapper.getAll();
    }

    @Transactional
    @Override
    public void patchDelete(Long[] ids) {
        paramMapper.patchDelete(ids);
    }

    @Override
    public PageInfo<Param> pageQuery(ParamQuery query) {
        //原生的写法：1.先查询总页数  2.再根据分页的信息查询当前页的数据
        //PageHelper的写法：开启分页
//                PageHelper.startPage(当前页,每页显示的条数);
        PageHelper.startPage(query.getCurrentPage(), query.getPageSize());
        //分页查询：只要开启了分页，它会帮助我们做什么事情？
        //1.先查询总数量  //2.根据application.yml中驱动名自动实现分页，如果是mysql就用limit
        //3.自动计算limit的第一个值：limit a,b [a = 当前页的起始下标 = (当前页-1)*每页显示的条数]
//        List<Emp> emps = empMapper.pageQuery(empQuery);
        List<Param> list = paramMapper.pageQuery(query);
        return new PageInfo(list);
    }

    @Override
    public Map<String, Object> getParams() {
        Map<String, Object> map = new HashMap<>();
        List<Param> params = paramMapper.getAll();
        for (Param param : params) {
            map.put(param.getParamKey(),param.getParamValue());
        }
        return map;
    }


}
